import React, { useEffect, useState } from "react";
import Item from './Item'
import CollectionModal from './CollectionModal.js'

import {
	Box,
	Image,
} from "@chakra-ui/react";
export default function Home({ defaultLinks=[]}) {
	const [quickLinkArray, setQuickLinkArray] = useState([]);
	useEffect(() => {
		let quickLinksStorage = window.localStorage.getItem("ql");
		if (quickLinksStorage) {
			quickLinksStorage = JSON.parse(quickLinksStorage);
		} else {
			window.localStorage.setItem("ql", JSON.stringify(defaultLinks));
			quickLinksStorage = defaultLinks;
		}
		setQuickLinkArray(quickLinksStorage);
	}, []);
	useEffect(()=>{
		document.addEventListener('click',()=>{
			setQuickLinkArray(quickLinksStorage=>{
				for(let i=0;i<quickLinksStorage.length;i++){
					quickLinksStorage[i].status = false;
				};
				return [...quickLinksStorage];
			});
		});
	},[])
	const getFaviconByWebUrl = (url) => {
		if (typeof document !== "undefined") {
			let a = document.createElement("a");
			a.href = url;
			let icon = a.protocol + "//" + a.hostname + "/favicon.ico";
			return icon;
		}
		return "";
	};

	const addQuickLink = (newLink) => {
		let icon = getFaviconByWebUrl(newLink.url);
		quickLinkArray.push({
			name: newLink.name,
			link: newLink.url,
			icon,
			status:false,
		});
		setQuickLinkArray([...quickLinkArray]);
		window.localStorage.setItem("ql", JSON.stringify(quickLinkArray));
	};
	const swithStatus = (index,e) => {
		setQuickLinkArray( quickLinkArray => {
			for(let i=0;i<quickLinkArray.length;i++){
				quickLinkArray[i].status = false;
			};
			quickLinkArray[index].status = true;
			return [...quickLinkArray]
		});
		e.stopPropagation();
		
	};

  	const handleDelete = (target) => {
		const newList = quickLinkArray.filter(item => item.link !== target.link)
		setQuickLinkArray([...newList]);
		window.localStorage.setItem("ql", JSON.stringify(newList));
  	};

	return (
		<div>
			<Box w="100%" h="100vh" overflow="hidden">
				<Box w="1200px" margin="0 auto">
					<Box
						w="100%"
						mt="180px"
						display="flex"
						justifyContent="center"
						alignItems="center"
					>
						<Image
							src="/images/google_img.png"
						/>
					</Box>

					<Box w="600px" margin="0 auto" mt="40px">
						{quickLinkArray.map((item,index) => {
							console.log(item);
							return (
								<Item
									key={index}
									data={item}
									index={index}
									changeStatus={swithStatus}
									onDelete={handleDelete}
								/>
							);
						})}

						<CollectionModal
							data={{
								name: "添加快捷方式",
								link: "https://www.baidu.com/",
								icon: "/images/plus.png",
							}}
							// onClick={onOpen}
							onAdd={addQuickLink}
						/>
					</Box>
				</Box>
			</Box>
		</div>
	);
}
